#include "ratingwidget.h"
#include <QDebug>
#include <QApplication>
#include <QInputDialog>
#include <QMessageBox>

RatingWidget::RatingWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_mainSplitter(nullptr)
    , m_ratableOrderGroup(nullptr)
    , m_ratableOrderLayout(nullptr)
    , m_ratableOrderTable(nullptr)
    , m_ratableOrderCountLabel(nullptr)
    , m_ratingHistoryGroup(nullptr)
    , m_ratingHistoryLayout(nullptr)
    , m_ratingHistoryTable(nullptr)
    , m_ratingHistoryCountLabel(nullptr)
    , m_statisticsGroup(nullptr)
    , m_statisticsLayout(nullptr)
    , m_totalRatingsLabel(nullptr)
    , m_averageRatingLabel(nullptr)
    , m_satisfactionRateLabel(nullptr)
    , m_ratingDistributionLabel(nullptr)
    , m_actionGroup(nullptr)
    , m_actionLayout(nullptr)
    , m_createRatingButton(nullptr)
    , m_editRatingButton(nullptr)
    , m_deleteRatingButton(nullptr)
    , m_refreshButton(nullptr)
    , m_ratingManager(nullptr)
    , m_orderManager(nullptr)
    , m_isInitialized(false)
    , m_isLoading(false)
{
    // 获取业务对象实例
    m_ratingManager = &RatingManager::instance();
    m_orderManager = &OrderManager::instance();
    
    initializeUI();
    
    // 连接信号槽
    connect(m_ratingManager, &RatingManager::ratingsChanged,
            this, &RatingWidget::onRatingsUpdated);
    
    // 监听订单状态变更，以便实时更新可评价订单
    connect(m_orderManager, &OrderManager::orderCompleted,
            this, &RatingWidget::onOrderCompleted);
    connect(m_orderManager, &OrderManager::orderStatusUpdated,
            this, [this](const QString& orderId, OrderStatus oldStatus, OrderStatus newStatus) {
                Q_UNUSED(orderId)
                Q_UNUSED(oldStatus)
                if (newStatus == OrderStatus::COMPLETED) {
                    // 当订单变为已完成时，刷新可评价订单列表
                    refreshRatings();
                }
            });
    
    // 监听订单数据文件变更（用于跨进程数据同步）
    connect(m_orderManager, &OrderManager::ordersChanged,
            this, [this]() {
                refreshRatings();
            });
    
    m_isInitialized = true;
}

RatingWidget::~RatingWidget()
{
    // Qt会自动清理子组件
}

void RatingWidget::setUserName(const QString& userName)
{
    if (m_currentUserName != userName) {
        m_currentUserName = userName;
        if (m_isInitialized) {
            refreshRatings();
        }
    }
}

void RatingWidget::refreshRatings()
{
    if (m_currentUserName.isEmpty()) {
        clearData();
        return;
    }
    
    // 防止重复刷新
    if (m_isLoading) {

        return;
    }
    

    
    m_isLoading = true;
    updateUIState();
    
    try {
        // 加载数据
        loadRatableOrders();
        loadRatingHistory();
        // 不再需要统计功能
        // updateRatingStatistics();
        

    } catch (...) {

    }
    
    m_isLoading = false;
    updateUIState();
}

void RatingWidget::clearData()
{
    m_ratableOrders.clear();
    m_ratingHistory.clear();
    m_statistics = RatingStatistics();
    
    if (m_ratableOrderTable) {
        m_ratableOrderTable->setRowCount(0);
    }
    if (m_ratingHistoryTable) {
        m_ratingHistoryTable->setRowCount(0);
    }
    
    updateUIState();
}

void RatingWidget::onRatingsUpdated()
{
    if (!m_currentUserName.isEmpty()) {
        refreshRatings();
    }
}

void RatingWidget::onOperationError(const QString& errorMessage)
{
    showOperationResult(errorMessage, false);
}

void RatingWidget::onRefreshButtonClicked()
{
    refreshRatings();
    showOperationResult("数据已刷新");
}

void RatingWidget::onCreateRatingClicked()
{
    Order selectedOrder = getSelectedRatableOrder();
    if (selectedOrder.id.isEmpty()) {
        QMessageBox::information(this, "提示", "请选择要评价的订单");
        return;
    }
    
    showRatingDialog(selectedOrder.id);
}

void RatingWidget::onEditRatingClicked()
{
    Rating selectedRating = getSelectedRating();
    if (selectedRating.id.isEmpty()) {
        QMessageBox::information(this, "提示", "请选择要编辑的评价");
        return;
    }
    
    showRatingDialog(selectedRating.orderId, selectedRating);
}

void RatingWidget::onDeleteRatingClicked()
{
    Rating selectedRating = getSelectedRating();
    if (selectedRating.id.isEmpty()) {
        QMessageBox::information(this, "提示", "请选择要删除的评价");
        return;
    }
    
    int ret = QMessageBox::question(this, "确认删除", 
                                   "确定要删除这条评价吗？\n\n此操作不可撤销。",
                                   QMessageBox::Yes | QMessageBox::No,
                                   QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        RatingOperationResult result = m_ratingManager->deleteRating(selectedRating.id);
        if (result == RatingOperationResult::SUCCESS) {
            showOperationResult("评价删除成功");
            refreshRatings();
        } else {
            showOperationResult(RatingManager::getOperationResultMessage(result), false);
        }
    }
}

void RatingWidget::onRatableOrderSelectionChanged()
{
    updateUIState();
}

void RatingWidget::onRatingHistorySelectionChanged()
{
    updateUIState();
}

void RatingWidget::onRatableOrderDoubleClicked(int row, int column)
{
    Q_UNUSED(column)
    
    if (row >= 0 && row < m_ratableOrders.size()) {
        const Order& order = m_ratableOrders[row];
        showRatingDialog(order.id);
    }
}

void RatingWidget::onRatingHistoryDoubleClicked(int row, int column)
{
    Q_UNUSED(column)
    
    if (row >= 0 && row < m_ratingHistory.size()) {
        const Rating& rating = m_ratingHistory[row];
        showRatingDialog(rating.orderId, rating);
    }
}

void RatingWidget::onFilterChanged()
{
    // 暂时不实现复杂的筛选功能，保持简单
    refreshRatings();
}

void RatingWidget::onStarClicked()
{
    QPushButton* starBtn = qobject_cast<QPushButton*>(sender());
    if (!starBtn) return;
    
    // 防止重复点击
    if (m_isLoading) {

        return;
    }
    
    QString orderId = starBtn->property("orderId").toString();
    int starIndex = starBtn->property("starIndex").toInt();
    int rating = starIndex + 1; // 转换为1-5的评分
    
    if (orderId.isEmpty()) {

        return;
    }
    

    
    // 设置加载状态，防止重复操作
    m_isLoading = true;
    updateUIState();
    
    try {
        // 快速评价
        auto result = m_ratingManager->createRating(orderId, m_currentUserName, rating, "快速评价");
        
        if (result.first == RatingOperationResult::SUCCESS) {
            showOperationResult("评价成功！感谢您的反馈", true);
            // 延迟刷新，避免立即刷新导致的问题
            QTimer::singleShot(100, this, [this]() {
                m_isLoading = false;
                refreshRatings();
            });
        } else {
            m_isLoading = false;
            updateUIState();
            showOperationResult(QString("评价失败: %1").arg(result.second), false);
        }
    } catch (...) {
        m_isLoading = false;
        updateUIState();
        showOperationResult("评价时发生未知错误", false);
        qDebug() << "Exception occurred during rating creation";
    }
}

void RatingWidget::onStarHovered()
{
    QPushButton* starBtn = qobject_cast<QPushButton*>(sender());
    if (!starBtn) return;
    
    QString orderId = starBtn->property("orderId").toString();
    int starIndex = starBtn->property("starIndex").toInt();
    
    // 更新这个订单卡片中的星级显示
    updateStarDisplay(orderId, starIndex + 1, true);
}

void RatingWidget::onQuickRateClicked()
{
    QPushButton* rateBtn = qobject_cast<QPushButton*>(sender());
    if (!rateBtn) return;
    
    // 防止重复点击
    if (m_isLoading) {

        return;
    }
    
    QString orderId = rateBtn->property("orderId").toString();
    
    if (orderId.isEmpty()) {

        return;
    }
    

    
    // 找到对应的订单
    Order selectedOrder;
    for (const Order& order : m_ratableOrders) {
        if (order.id == orderId) {
            selectedOrder = order;
            break;
        }
    }
    
    if (!selectedOrder.id.isEmpty()) {
        showRatingDialog(orderId, Rating());
    }
}

void RatingWidget::updateStarDisplay(const QString& orderId, int rating, bool isHover)
{
    // 查找对应订单卡片中的星级按钮并更新显示
    QList<QPushButton*> starButtons = findChildren<QPushButton*>();
    
    for (QPushButton* btn : starButtons) {
        if (btn->property("orderId").toString() == orderId) {
            int starIndex = btn->property("starIndex").toInt();
            
            if (isHover) {
                // 悬停效果
                if (starIndex < rating) {
                    btn->setText("★");
                    btn->setStyleSheet(btn->styleSheet() + "color: #ffd700;");
                } else {
                    btn->setText("☆");
                    btn->setStyleSheet(btn->styleSheet() + "color: #ddd;");
                }
            } else {
                // 恢复默认状态
                btn->setText("☆");
                btn->setStyleSheet(btn->styleSheet() + "color: #ddd;");
            }
        }
    }
}

void RatingWidget::initializeUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);
    
    // 创建标题栏
    createTitleBar();
    
    // 创建主滚动区域
    QScrollArea* mainScrollArea = new QScrollArea(this);
    mainScrollArea->setWidgetResizable(true);
    mainScrollArea->setFrameShape(QFrame::NoFrame);
    mainScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    mainScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    
    // 创建滚动内容容器
    QWidget* scrollContent = new QWidget();
    QVBoxLayout* scrollLayout = new QVBoxLayout(scrollContent);
    scrollLayout->setContentsMargins(15, 15, 15, 15);
    scrollLayout->setSpacing(12);
    
    // 创建可评价订单卡片区域
    createRatableOrderCardsArea();
    
    // 将订单卡片区域添加到滚动布局
    scrollLayout->addWidget(m_ratableOrderGroup);
    scrollLayout->addStretch(); // 添加弹性空间
    
    // 设置滚动内容
    scrollContent->setMinimumSize(600, 400);
    mainScrollArea->setWidget(scrollContent);
    m_mainLayout->addWidget(mainScrollArea);
    
    // 应用样式
    applyStyleSheet();
    
    // 更新界面状态
    updateUIState();
}

void RatingWidget::createTitleBar()
{
    // 创建标题栏容器
    QWidget* titleWidget = new QWidget(this);
    titleWidget->setFixedHeight(60);
    titleWidget->setStyleSheet("background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;");
    
    QHBoxLayout* titleLayout = new QHBoxLayout(titleWidget);
    titleLayout->setContentsMargins(20, 0, 20, 0);
    titleLayout->setSpacing(15);
    
    // 创建标题
    QLabel* titleLabel = new QLabel("订单评价", titleWidget);
    titleLabel->setStyleSheet("color: white; font-size: 18px; font-weight: bold;");
    
    // 创建副标题
    QLabel* subtitleLabel = new QLabel("为您的用餐体验打分", titleWidget);
    subtitleLabel->setStyleSheet("color: rgba(255, 255, 255, 0.8); font-size: 12px;");
    
    // 创建统计标签
    m_ratableOrderCountLabel = new QLabel("待评价: 0", titleWidget);
    m_ratableOrderCountLabel->setStyleSheet("color: white; font-size: 14px; background: rgba(255,255,255,0.2); padding: 5px 12px; border-radius: 15px;");
    
    titleLayout->addWidget(titleLabel);
    titleLayout->addWidget(subtitleLabel);
    titleLayout->addStretch();
    titleLayout->addWidget(m_ratableOrderCountLabel);
    
    m_mainLayout->addWidget(titleWidget);
}

void RatingWidget::createRatableOrderCardsArea()
{
    m_ratableOrderGroup = new QGroupBox(this);
    m_ratableOrderGroup->setStyleSheet("QGroupBox { border: none; background: transparent; }");
    m_ratableOrderLayout = new QVBoxLayout(m_ratableOrderGroup);
    m_ratableOrderLayout->setContentsMargins(0, 0, 0, 0);
    m_ratableOrderLayout->setSpacing(15);
    
    // 创建空状态提示
    m_emptyStateWidget = new QWidget(this);
    QVBoxLayout* emptyLayout = new QVBoxLayout(m_emptyStateWidget);
    emptyLayout->setAlignment(Qt::AlignCenter);
    emptyLayout->setSpacing(20);
    
    QLabel* emptyIcon = new QLabel("🍽️", m_emptyStateWidget);
    emptyIcon->setAlignment(Qt::AlignCenter);
    emptyIcon->setStyleSheet("font-size: 48px;");
    
    QLabel* emptyText = new QLabel("暂无可评价的订单", m_emptyStateWidget);
    emptyText->setAlignment(Qt::AlignCenter);
    emptyText->setStyleSheet("color: #999; font-size: 16px;");
    
    QLabel* emptyHint = new QLabel("完成订单后即可在此进行评价", m_emptyStateWidget);
    emptyHint->setAlignment(Qt::AlignCenter);
    emptyHint->setStyleSheet("color: #ccc; font-size: 12px;");
    
    emptyLayout->addWidget(emptyIcon);
    emptyLayout->addWidget(emptyText);
    emptyLayout->addWidget(emptyHint);
    
    m_ratableOrderLayout->addWidget(m_emptyStateWidget);
}

void RatingWidget::createRatableOrdersArea()
{
    m_ratableOrderGroup = new QGroupBox("可评价订单", this);
    m_ratableOrderLayout = new QVBoxLayout(m_ratableOrderGroup);
    m_ratableOrderLayout->setContentsMargins(15, 15, 15, 15);
    m_ratableOrderLayout->setSpacing(10);
    
    // 设置GroupBox的固定高度
    m_ratableOrderGroup->setMinimumHeight(320);
    m_ratableOrderGroup->setMaximumHeight(400);
    m_ratableOrderGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    
    // 创建表格的滚动区域
    QScrollArea* tableScrollArea = new QScrollArea();
    tableScrollArea->setWidgetResizable(true);
    tableScrollArea->setFrameShape(QFrame::NoFrame);
    tableScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    tableScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    
    // 创建表格
    m_ratableOrderTable = new QTableWidget();
    m_ratableOrderTable->setColumnCount(COL_RATABLE_COUNT);
    
    QStringList headers = {"订单编号", "下单时间", "订单金额", "菜品数量"};
    m_ratableOrderTable->setHorizontalHeaderLabels(headers);
    
    // 设置表格的最小尺寸
    m_ratableOrderTable->setMinimumHeight(200);
    
    // 连接信号
    connect(m_ratableOrderTable, &QTableWidget::itemSelectionChanged,
            this, &RatingWidget::onRatableOrderSelectionChanged);
    connect(m_ratableOrderTable, &QTableWidget::cellDoubleClicked,
            this, &RatingWidget::onRatableOrderDoubleClicked);
    
    // 将表格放入滚动区域
    tableScrollArea->setWidget(m_ratableOrderTable);
    m_ratableOrderLayout->addWidget(tableScrollArea);
    
    // 创建统计标签和说明
    QHBoxLayout* ratableCountLayout = new QHBoxLayout();
    m_ratableOrderCountLabel = new QLabel("可评价订单: 0", this);
    QLabel* ratableHintLabel = new QLabel("双击订单可直接评价", this);
    ratableHintLabel->setStyleSheet("color: #666666; font-size: 10px;");
    
    ratableCountLayout->addWidget(m_ratableOrderCountLabel);
    ratableCountLayout->addStretch();
    ratableCountLayout->addWidget(ratableHintLabel);
    
    m_ratableOrderLayout->addLayout(ratableCountLayout);
}

void RatingWidget::createRatingHistoryArea()
{
    m_ratingHistoryGroup = new QGroupBox("评价历史", this);
    m_ratingHistoryLayout = new QVBoxLayout(m_ratingHistoryGroup);
    m_ratingHistoryLayout->setContentsMargins(15, 15, 15, 15);
    m_ratingHistoryLayout->setSpacing(10);
    
    // 设置GroupBox的固定高度
    m_ratingHistoryGroup->setMinimumHeight(320);
    m_ratingHistoryGroup->setMaximumHeight(400);
    m_ratingHistoryGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    
    // 创建表格的滚动区域
    QScrollArea* historyScrollArea = new QScrollArea();
    historyScrollArea->setWidgetResizable(true);
    historyScrollArea->setFrameShape(QFrame::NoFrame);
    historyScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    historyScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    
    // 创建表格
    m_ratingHistoryTable = new QTableWidget();
    m_ratingHistoryTable->setColumnCount(COL_RATING_HISTORY_COUNT);
    
    QStringList headers = {"订单编号", "评分", "评价内容", "评价时间"};
    m_ratingHistoryTable->setHorizontalHeaderLabels(headers);
    
    // 设置表格的最小尺寸
    m_ratingHistoryTable->setMinimumHeight(200);
    
    // 连接信号
    connect(m_ratingHistoryTable, &QTableWidget::itemSelectionChanged,
            this, &RatingWidget::onRatingHistorySelectionChanged);
    connect(m_ratingHistoryTable, &QTableWidget::cellDoubleClicked,
            this, &RatingWidget::onRatingHistoryDoubleClicked);
    
    // 将表格放入滚动区域
    historyScrollArea->setWidget(m_ratingHistoryTable);
    m_ratingHistoryLayout->addWidget(historyScrollArea);
    
    // 创建统计标签和说明
    QHBoxLayout* historyCountLayout = new QHBoxLayout();
    m_ratingHistoryCountLabel = new QLabel("评价历史: 0", this);
    QLabel* historyHintLabel = new QLabel("双击评价可编辑", this);
    historyHintLabel->setStyleSheet("color: #666666; font-size: 10px;");
    
    historyCountLayout->addWidget(m_ratingHistoryCountLabel);
    historyCountLayout->addStretch();
    historyCountLayout->addWidget(historyHintLabel);
    
    m_ratingHistoryLayout->addLayout(historyCountLayout);
}

void RatingWidget::createRatingStatisticsArea()
{
    m_statisticsGroup = new QGroupBox("评价统计", this);
    m_statisticsLayout = new QVBoxLayout(m_statisticsGroup);
    m_statisticsLayout->setContentsMargins(12, 12, 12, 12);
    m_statisticsLayout->setSpacing(10);
    
    // 创建基本统计信息
    m_totalRatingsLabel = new QLabel("总评价数: 0", this);
    m_averageRatingLabel = new QLabel("平均评分: 0.0", this);
    m_satisfactionRateLabel = new QLabel("满意度: 0.0%", this);
    
    // 创建评分分布标签 - 使用更紧凑的格式
    m_ratingDistributionLabel = new QLabel("评分分布: ", this);
    m_ratingDistributionLabel->setWordWrap(true); // 允许换行
    
    // 设置适中的字体大小
    QFont normalFont;
    normalFont.setPointSize(10);
    m_totalRatingsLabel->setFont(normalFont);
    m_averageRatingLabel->setFont(normalFont);
    m_satisfactionRateLabel->setFont(normalFont);
    m_ratingDistributionLabel->setFont(normalFont);
    
    m_statisticsLayout->addWidget(m_totalRatingsLabel);
    m_statisticsLayout->addWidget(m_averageRatingLabel);
    m_statisticsLayout->addWidget(m_satisfactionRateLabel);
    m_statisticsLayout->addWidget(m_ratingDistributionLabel);
    m_statisticsLayout->addStretch(); // 添加弹性空间
}

void RatingWidget::createActionArea()
{
    m_actionGroup = new QGroupBox("操作", this);
    m_actionLayout = new QHBoxLayout(m_actionGroup);
    m_actionLayout->setContentsMargins(25, 20, 25, 20);
    m_actionLayout->setSpacing(20);
    
    // 设置操作区域固定在底部，不参与滚动
    m_actionGroup->setFixedHeight(80);
    m_actionGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    
    m_createRatingButton = new QPushButton("评价订单", this);
    m_editRatingButton = new QPushButton("编辑评价", this);
    m_deleteRatingButton = new QPushButton("删除评价", this);
    m_refreshButton = new QPushButton("刷新数据", this);
    
    // 设置按钮舒适的大小
    m_createRatingButton->setFixedHeight(35);
    m_editRatingButton->setFixedHeight(35);
    m_deleteRatingButton->setFixedHeight(35);
    m_refreshButton->setFixedHeight(35);
    
    m_createRatingButton->setMinimumWidth(100);
    m_editRatingButton->setMinimumWidth(100);
    m_deleteRatingButton->setMinimumWidth(100);
    m_refreshButton->setMinimumWidth(100);
    
    // 连接信号
    connect(m_createRatingButton, &QPushButton::clicked,
            this, &RatingWidget::onCreateRatingClicked);
    connect(m_editRatingButton, &QPushButton::clicked,
            this, &RatingWidget::onEditRatingClicked);
    connect(m_deleteRatingButton, &QPushButton::clicked,
            this, &RatingWidget::onDeleteRatingClicked);
    connect(m_refreshButton, &QPushButton::clicked,
            this, &RatingWidget::onRefreshButtonClicked);
    
    // 水平排列按钮
    m_actionLayout->addWidget(m_createRatingButton);
    m_actionLayout->addWidget(m_editRatingButton);
    m_actionLayout->addWidget(m_deleteRatingButton);
    m_actionLayout->addStretch(); // 添加弹性空间
    m_actionLayout->addWidget(m_refreshButton);
}

void RatingWidget::applyStyleSheet()
{
    setStyleSheet(R"(
        QWidget {
            background-color: #f8f9fa;
        }
        
        QScrollArea {
            border: none;
            background-color: transparent;
        }
        
        QScrollBar:vertical {
            background: #f1f1f1;
            width: 8px;
            border-radius: 4px;
        }
        
        QScrollBar::handle:vertical {
            background: #c1c1c1;
            min-height: 20px;
            border-radius: 4px;
        }
        
        QScrollBar::handle:vertical:hover {
            background: #a8a8a8;
        }
        
        QScrollBar::add-line:vertical,
        QScrollBar::sub-line:vertical {
            border: none;
            background: none;
        }
        
        QScrollBar:horizontal {
            background: #f1f1f1;
            height: 8px;
            border-radius: 4px;
        }
        
        QScrollBar::handle:horizontal {
            background: #c1c1c1;
            min-width: 20px;
            border-radius: 4px;
        }
        
        QScrollBar::handle:horizontal:hover {
            background: #a8a8a8;
        }
        
        QScrollBar::add-line:horizontal,
        QScrollBar::sub-line:horizontal {
            border: none;
            background: none;
        }
    )");
}

void RatingWidget::setupTableProperties()
{
    if (m_ratableOrderTable) {
        m_ratableOrderTable->setAlternatingRowColors(true);
        m_ratableOrderTable->setSelectionBehavior(QAbstractItemView::SelectRows);
        m_ratableOrderTable->setSelectionMode(QAbstractItemView::SingleSelection);
        m_ratableOrderTable->verticalHeader()->setVisible(false);
        
        // 设置表格自适应列宽
        m_ratableOrderTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        
        // 设置最小列宽，确保内容可见
        m_ratableOrderTable->horizontalHeader()->setMinimumSectionSize(80);
        
        // 设置更舒适的行高
        m_ratableOrderTable->verticalHeader()->setDefaultSectionSize(45);
        
        // 设置表格的最小高度
        m_ratableOrderTable->setMinimumHeight(200);
    }
    
    if (m_ratingHistoryTable) {
        m_ratingHistoryTable->setAlternatingRowColors(true);
        m_ratingHistoryTable->setSelectionBehavior(QAbstractItemView::SelectRows);
        m_ratingHistoryTable->setSelectionMode(QAbstractItemView::SingleSelection);
        m_ratingHistoryTable->verticalHeader()->setVisible(false);
        
        // 设置表格自适应列宽
        m_ratingHistoryTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        
        // 设置最小列宽，确保内容可见
        m_ratingHistoryTable->horizontalHeader()->setMinimumSectionSize(60);
        
        // 对于评分列，设置固定宽度
        m_ratingHistoryTable->horizontalHeader()->setSectionResizeMode(COL_RATING, QHeaderView::Fixed);
        m_ratingHistoryTable->setColumnWidth(COL_RATING, 60);
        
        // 设置更舒适的行高
        m_ratingHistoryTable->verticalHeader()->setDefaultSectionSize(45);
        
        // 设置表格的最小高度
        m_ratingHistoryTable->setMinimumHeight(200);
    }
}

void RatingWidget::loadRatableOrders()
{
    if (m_currentUserName.isEmpty()) {
        return;
    }
    
    // 通过用户名查找用户ID
    Customer customer = DataManager::instance().getCustomerByUsername(m_currentUserName);
    if (customer.id.isEmpty()) {
        m_ratableOrders.clear();
        return;
    }
    
    // 获取用户的已完成但未评价的订单
    QList<Order> allOrders = m_orderManager->getOrdersByCustomerId(customer.id);
    m_ratableOrders.clear();
    
    for (const Order& order : allOrders) {
        if (order.status == OrderStatus::COMPLETED && 
            !m_ratingManager->isOrderRated(order.id)) {
            m_ratableOrders.append(order);
        }
    }
    
    // 创建订单卡片
    createOrderCards(m_ratableOrders);
    
    // 更新标题栏统计
    if (m_ratableOrderCountLabel) {
        m_ratableOrderCountLabel->setText(QString("待评价: %1").arg(m_ratableOrders.size()));
    }
    
    // 显示/隐藏空状态
    if (m_emptyStateWidget) {
        m_emptyStateWidget->setVisible(m_ratableOrders.isEmpty());
    }
}

void RatingWidget::createOrderCards(const QList<Order>& orders)
{
    // 清除现有的卡片
    clearOrderCards();
    
    for (const Order& order : orders) {
        // 创建阴影容器
        QWidget* shadowContainer = new QWidget();
        shadowContainer->setStyleSheet(R"(
            QWidget {
                background: #f0f0f0;
                border-radius: 14px;
                margin: 2px;
            }
        )");
        shadowContainer->setMinimumHeight(180);
        shadowContainer->setMaximumHeight(240);
        
        QVBoxLayout* shadowLayout = new QVBoxLayout(shadowContainer);
        shadowLayout->setContentsMargins(2, 2, 2, 2);
        
        // 创建订单卡片
        QWidget* orderCard = new QWidget();
        orderCard->setStyleSheet(R"(
            QWidget {
                background: white;
                border: 1px solid #e8e8e8;
                border-radius: 12px;
            }
            QWidget:hover {
                border: 2px solid #667eea;
                background: #f8f9ff;
            }
        )");
        orderCard->setMinimumHeight(176);
        orderCard->setMaximumHeight(236);
        
        shadowLayout->addWidget(orderCard);
        
        // 创建卡片布局
        QHBoxLayout* cardLayout = new QHBoxLayout(orderCard);
        cardLayout->setContentsMargins(15, 12, 15, 12);
        cardLayout->setSpacing(15);
        
        // 左侧：菜品图片区域
        QWidget* imageArea = createFoodImagesArea(order);
        imageArea->setFixedWidth(120);
        
        // 中间：订单信息
        QVBoxLayout* centerLayout = new QVBoxLayout();
        centerLayout->setSpacing(8);
        
        // 订单编号和时间
        QLabel* orderIdLabel = new QLabel(QString("订单编号: %1").arg(order.id));
        orderIdLabel->setStyleSheet("color: #333; font-size: 14px; font-weight: bold; border: none; background: transparent;");
        
        QLabel* timeLabel = new QLabel(QString("下单时间: %1").arg(order.createdDate.toString("yyyy-MM-dd hh:mm")));
        timeLabel->setStyleSheet("color: #666; font-size: 12px; border: none; background: transparent;");
        
        // 订单金额
        QLabel* amountLabel = new QLabel(QString("￥%1").arg(order.totalAmount, 0, 'f', 2));
        amountLabel->setStyleSheet("color: #ff6b35; font-size: 18px; font-weight: bold; border: none; background: transparent;");
        
        // 菜品信息
        QString itemsText = QString("共%1道菜品").arg(order.items.size());
        if (!order.items.isEmpty()) {
            QStringList itemNames;
            for (int i = 0; i < qMin(3, order.items.size()); ++i) {
                itemNames << order.items[i].menuItemName;
            }
            if (order.items.size() > 3) {
                itemNames << "...";
            }
            itemsText += " | " + itemNames.join("、");
        }
        
        QLabel* itemsLabel = new QLabel(itemsText);
        itemsLabel->setStyleSheet("color: #888; font-size: 11px; border: none; background: transparent;");
        itemsLabel->setWordWrap(true);
        
        centerLayout->addWidget(orderIdLabel);
        centerLayout->addWidget(timeLabel);
        centerLayout->addWidget(amountLabel);
        centerLayout->addWidget(itemsLabel);
        centerLayout->addStretch();
        
        // 右侧：创建独立的评价区域Widget
        QWidget* rightWidget = new QWidget();
        rightWidget->setMinimumWidth(150);
        rightWidget->setMaximumWidth(180);
        rightWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
        rightWidget->setStyleSheet("QWidget { background: transparent; border: none; }");
        
        QVBoxLayout* rightLayout = new QVBoxLayout(rightWidget);
        rightLayout->setAlignment(Qt::AlignTop | Qt::AlignHCenter);
        rightLayout->setSpacing(15);
        rightLayout->setContentsMargins(10, 15, 10, 15);
        
        // 星级展示区域
        QWidget* starsWidget = new QWidget();
        starsWidget->setFixedHeight(40);
        starsWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
        QHBoxLayout* starsLayout = new QHBoxLayout(starsWidget);
        starsLayout->setContentsMargins(0, 0, 0, 0);
        starsLayout->setSpacing(3);
        starsLayout->setAlignment(Qt::AlignCenter);
        
        // 创建5个星级按钮
        for (int i = 0; i < 5; ++i) {
            QPushButton* starBtn = new QPushButton("☆");
            starBtn->setFixedSize(28, 28);
            starBtn->setStyleSheet(R"(
                QPushButton {
                    border: none;
                    background: transparent;
                    color: #ddd;
                    font-size: 20px;
                }
                QPushButton:hover {
                    color: #ffd700;
                }
            )");
            starBtn->setProperty("starIndex", i);
            starBtn->setProperty("orderId", order.id);
            
            connect(starBtn, &QPushButton::clicked, this, &RatingWidget::onStarClicked);
            starsLayout->addWidget(starBtn);
        }
        
        // 评价按钮 - 灰白色背景，黑色字体
        QPushButton* rateBtn = new QPushButton("立即评价");
        rateBtn->setFixedHeight(36);
        rateBtn->setMinimumWidth(100);
        rateBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
        

        rateBtn->setStyleSheet(R"(
            QPushButton {
                background: #f5f5f5;
                color: #333333;
                border: 1px solid #e0e0e0;
                border-radius: 18px;
                padding: 8px 16px;
                font-size: 13px;
                font-weight: normal;
            }
            QPushButton:hover {
                background: #eeeeee;
                border: 1px solid #d0d0d0;
            }
            QPushButton:pressed {
                background: #e8e8e8;
                border: 1px solid #c0c0c0;
            }
        )");
        rateBtn->setProperty("orderId", order.id);
        connect(rateBtn, &QPushButton::clicked, this, &RatingWidget::onQuickRateClicked);
        
        rightLayout->addWidget(starsWidget);
        rightLayout->addWidget(rateBtn);
        rightLayout->addStretch();
        
        // 添加到卡片布局
        cardLayout->addWidget(imageArea);
        cardLayout->addLayout(centerLayout, 3);
        cardLayout->addWidget(rightWidget);
        
        // 添加到主布局
        m_ratableOrderLayout->addWidget(shadowContainer);
    }
}

void RatingWidget::clearOrderCards()
{

    
    // 先断开所有按钮的信号连接，防止删除时触发信号
    QList<QPushButton*> buttons = findChildren<QPushButton*>();
    for (QPushButton* btn : buttons) {
        if (btn->property("orderId").isValid()) {
            btn->disconnect();
        }
    }
    
    // 清除除了空状态widget之外的所有子控件
    QList<QWidget*> widgetsToDelete;
    
    for (int i = m_ratableOrderLayout->count() - 1; i >= 0; --i) {
        QLayoutItem* item = m_ratableOrderLayout->itemAt(i);
        if (item && item->widget() && item->widget() != m_emptyStateWidget) {
            widgetsToDelete.append(item->widget());
            m_ratableOrderLayout->removeItem(item);
        }
    }
    
    // 延迟删除widgets，避免立即删除导致的问题
    for (QWidget* widget : widgetsToDelete) {
        widget->setParent(nullptr);
        widget->deleteLater();
    }
    
    // 重新添加空状态widget
    if (m_emptyStateWidget && m_ratableOrderLayout->indexOf(m_emptyStateWidget) == -1) {
        m_ratableOrderLayout->addWidget(m_emptyStateWidget);
    }
    

}

QWidget* RatingWidget::createFoodImagesArea(const Order& order)
{
    QWidget* imageArea = new QWidget();
    imageArea->setStyleSheet("QWidget { background: transparent; border: none; }");
    
    QVBoxLayout* imageLayout = new QVBoxLayout(imageArea);
    imageLayout->setContentsMargins(5, 5, 5, 5);
    imageLayout->setSpacing(5);
    
    // 创建网格布局来显示菜品图片
    QGridLayout* gridLayout = new QGridLayout();
    gridLayout->setSpacing(3);
    
    int maxImages = 4; // 最多显示4张图片
    int imageCount = 0;
    
    for (int i = 0; i < order.items.size() && imageCount < maxImages; ++i) {
        const OrderItem& item = order.items[i];
        
        // 创建菜品图片标签
        QLabel* imageLabel = new QLabel();
        imageLabel->setFixedSize(50, 50);
        imageLabel->setScaledContents(true);
        imageLabel->setStyleSheet(R"(
            QLabel {
                border: 1px solid #ddd;
                border-radius: 8px;
                background: #f8f9fa;
                border: none;
            }
        )");
        
        // 设置默认图片或根据菜品类型设置图片
        QString defaultImage = getDefaultFoodImage(item.menuItemName);
        imageLabel->setText(defaultImage);
        imageLabel->setAlignment(Qt::AlignCenter);
        imageLabel->setFont(QFont("Arial", 20));
        
        // 添加到网格布局
        int row = imageCount / 2;
        int col = imageCount % 2;
        gridLayout->addWidget(imageLabel, row, col);
        
        imageCount++;
    }
    
    // 如果有更多菜品，显示"更多"指示
    if (order.items.size() > maxImages) {
        QLabel* moreLabel = new QLabel(QString("+%1").arg(order.items.size() - maxImages));
        moreLabel->setFixedSize(50, 50);
        moreLabel->setAlignment(Qt::AlignCenter);
        moreLabel->setStyleSheet(R"(
            QLabel {
                border: 1px solid #ddd;
                border-radius: 8px;
                background: #e9ecef;
                color: #666;
                font-size: 12px;
                font-weight: bold;
                border: none;
            }
        )");
        
        int row = (maxImages - 1) / 2;
        int col = (maxImages - 1) % 2;
        gridLayout->addWidget(moreLabel, row, col);
    }
    
    imageLayout->addLayout(gridLayout);
    imageLayout->addStretch();
    
    return imageArea;
}

QString RatingWidget::getDefaultFoodImage(const QString& itemName)
{
    // 根据菜品名称返回对应的emoji图标
    QString name = itemName.toLower();
    
    if (name.contains("汤") || name.contains("soup")) {
        return "🍲";
    } else if (name.contains("面") || name.contains("noodle")) {
        return "🍜";
    } else if (name.contains("饭") || name.contains("rice")) {
        return "🍚";
    } else if (name.contains("鸡") || name.contains("chicken")) {
        return "🍗";
    } else if (name.contains("鱼") || name.contains("fish")) {
        return "🐟";
    } else if (name.contains("虾") || name.contains("shrimp")) {
        return "🍤";
    } else if (name.contains("牛") || name.contains("beef")) {
        return "🥩";
    } else if (name.contains("猪") || name.contains("pork")) {
        return "🥓";
    } else if (name.contains("蔬菜") || name.contains("vegetable")) {
        return "🥬";
    } else if (name.contains("沙拉") || name.contains("salad")) {
        return "🥗";
    } else if (name.contains("饮料") || name.contains("drink") || name.contains("茶") || name.contains("coffee")) {
        return "🥤";
    } else if (name.contains("甜品") || name.contains("dessert") || name.contains("蛋糕")) {
        return "🍰";
    } else if (name.contains("水果") || name.contains("fruit")) {
        return "🍎";
    } else {
        return "🍽️"; // 默认餐具图标
    }
}

void RatingWidget::loadRatingHistory()
{
    if (m_currentUserName.isEmpty()) {
        return;
    }
    
    m_ratingHistory = m_ratingManager->getRatingsByCustomerName(m_currentUserName);
    populateRatingHistoryTable(m_ratingHistory);
    
    if (m_ratingHistoryCountLabel) {
        m_ratingHistoryCountLabel->setText(QString("评价历史: %1").arg(m_ratingHistory.size()));
    }
}

void RatingWidget::updateRatingStatistics()
{
    if (m_currentUserName.isEmpty()) {
        m_statistics = RatingStatistics();
    } else {
        // 获取评价列表并手动计算统计信息
        QList<Rating> customerRatings = m_ratingManager->getRatingsByCustomerName(m_currentUserName);
        
        // 初始化统计信息
        m_statistics = RatingStatistics();
        m_statistics.totalRatings = customerRatings.size();
        
        if (!customerRatings.isEmpty()) {
            double totalRating = 0.0;
            for (const Rating& rating : customerRatings) {
                totalRating += rating.rating;
                if (rating.rating >= 1 && rating.rating <= 5) {
                    m_statistics.ratingDistribution[rating.rating - 1]++;
                }
            }
            m_statistics.averageRating = totalRating / customerRatings.size();
            
            // 计算满意度（4-5星比例）
            int satisfiedCount = m_statistics.ratingDistribution[3] + m_statistics.ratingDistribution[4];
            m_statistics.satisfactionRate = (customerRatings.size() > 0) ? 
                (satisfiedCount * 100.0 / customerRatings.size()) : 0.0;
        }
    }
    
    if (m_totalRatingsLabel) {
        m_totalRatingsLabel->setText(QString("总评价数: %1").arg(m_statistics.totalRatings));
    }
    
    if (m_averageRatingLabel) {
        m_averageRatingLabel->setText(QString("平均评分: %1").arg(
            QString::number(m_statistics.averageRating, 'f', 1)));
    }
    
    if (m_satisfactionRateLabel) {
        m_satisfactionRateLabel->setText(QString("满意度: %1%").arg(
            QString::number(m_statistics.satisfactionRate, 'f', 1)));
    }
    
    if (m_ratingDistributionLabel) {
        QString distribution = "评分分布:\n";
        for (int i = 0; i < 5; ++i) {
            int count = (i < m_statistics.ratingDistribution.size()) ? m_statistics.ratingDistribution[i] : 0;
            distribution += QString("%1★:%2").arg(i + 1).arg(count);
            if (i < 4) distribution += " ";
            if (i == 2) distribution += "\n"; // 在3星后换行
        }
        m_ratingDistributionLabel->setText(distribution);
    }
}

void RatingWidget::populateRatableOrderTable(const QList<Order>& orders)
{
    if (!m_ratableOrderTable) return;
    
    m_ratableOrderTable->setRowCount(orders.size());
    
    for (int row = 0; row < orders.size(); ++row) {
        const Order& order = orders[row];
        
        // 订单编号
        QTableWidgetItem* orderIdItem = new QTableWidgetItem(order.id);
        orderIdItem->setFlags(orderIdItem->flags() & ~Qt::ItemIsEditable);
        m_ratableOrderTable->setItem(row, COL_ORDER_ID, orderIdItem);
        
        // 下单时间
        QTableWidgetItem* createTimeItem = new QTableWidgetItem(formatDateTime(order.createdDate));
        createTimeItem->setFlags(createTimeItem->flags() & ~Qt::ItemIsEditable);
        m_ratableOrderTable->setItem(row, COL_CREATE_TIME, createTimeItem);
        
        // 订单金额
        QTableWidgetItem* amountItem = new QTableWidgetItem(formatAmount(order.totalAmount));
        amountItem->setFlags(amountItem->flags() & ~Qt::ItemIsEditable);
        amountItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        m_ratableOrderTable->setItem(row, COL_TOTAL_AMOUNT, amountItem);
        
        // 菜品数量
        QTableWidgetItem* itemCountItem = new QTableWidgetItem(QString::number(order.getTotalItems()));
        itemCountItem->setFlags(itemCountItem->flags() & ~Qt::ItemIsEditable);
        itemCountItem->setTextAlignment(Qt::AlignCenter);
        m_ratableOrderTable->setItem(row, COL_ITEM_COUNT, itemCountItem);
    }
}

void RatingWidget::populateRatingHistoryTable(const QList<Rating>& ratings)
{
    if (!m_ratingHistoryTable) return;
    
    m_ratingHistoryTable->setRowCount(ratings.size());
    
    for (int row = 0; row < ratings.size(); ++row) {
        const Rating& rating = ratings[row];
        
        // 订单编号
        QTableWidgetItem* orderIdItem = new QTableWidgetItem(rating.orderId);
        orderIdItem->setFlags(orderIdItem->flags() & ~Qt::ItemIsEditable);
        m_ratingHistoryTable->setItem(row, COL_RATING_ORDER_ID, orderIdItem);
        
        // 评分
        QTableWidgetItem* ratingItem = new QTableWidgetItem(
            RatingManager::formatRatingStars(rating.rating));
        ratingItem->setFlags(ratingItem->flags() & ~Qt::ItemIsEditable);
        ratingItem->setTextAlignment(Qt::AlignCenter);
        m_ratingHistoryTable->setItem(row, COL_RATING, ratingItem);
        
        // 评价内容
        QString comment = rating.comment;
        if (comment.length() > 50) {
            comment = comment.left(47) + "...";
        }
        QTableWidgetItem* commentItem = new QTableWidgetItem(comment);
        commentItem->setFlags(commentItem->flags() & ~Qt::ItemIsEditable);
        commentItem->setToolTip(rating.comment); // 完整内容作为提示
        m_ratingHistoryTable->setItem(row, COL_COMMENT, commentItem);
        
        // 评价时间
        QTableWidgetItem* timeItem = new QTableWidgetItem(formatDateTime(rating.createdDate));
        timeItem->setFlags(timeItem->flags() & ~Qt::ItemIsEditable);
        m_ratingHistoryTable->setItem(row, COL_RATING_TIME, timeItem);
    }
}

void RatingWidget::updateUIState()
{
    bool hasRatableSelection = false;
    bool hasRatingSelection = false;
    
    if (m_ratableOrderTable) {
        hasRatableSelection = m_ratableOrderTable->currentRow() >= 0;
    }
    
    if (m_ratingHistoryTable) {
        hasRatingSelection = m_ratingHistoryTable->currentRow() >= 0;
    }
    
    if (m_createRatingButton) {
        m_createRatingButton->setEnabled(hasRatableSelection && !m_isLoading);
    }
    
    if (m_editRatingButton) {
        m_editRatingButton->setEnabled(hasRatingSelection && !m_isLoading);
    }
    
    if (m_deleteRatingButton) {
        m_deleteRatingButton->setEnabled(hasRatingSelection && !m_isLoading);
    }
    
    if (m_refreshButton) {
        m_refreshButton->setEnabled(!m_isLoading);
    }
}

void RatingWidget::showOperationResult(const QString& message, bool success)
{
    // 暂时简化，避免模态对话框冲突导致卡死
    // 后续可以改为状态栏提示或其他非模态方式
    Q_UNUSED(message)
    Q_UNUSED(success)
}

void RatingWidget::showRatingDialog(const QString& orderId, const Rating& existingRating)
{
    RatingDialog* dialog = nullptr;
    
    if (existingRating.id.isEmpty()) {
        // 创建新评价
        dialog = new RatingDialog(orderId, this);
    } else {
        // 编辑现有评价
        dialog = new RatingDialog(existingRating, this);
    }
    
    if (dialog->exec() == QDialog::Accepted) {
        Rating rating = dialog->getRating();
        rating.customerName = m_currentUserName;
        
        if (existingRating.id.isEmpty()) {
            // 创建新评价
            auto createResult = m_ratingManager->createRating(orderId, m_currentUserName, 
                                                           rating.rating, rating.comment);
            if (createResult.first == RatingOperationResult::SUCCESS) {
                QMessageBox::information(this, "成功", "评价提交成功！");
                // 延迟刷新，避免潜在问题
                QTimer::singleShot(500, this, [this]() {
                    refreshRatings();
                });
            } else {
                QMessageBox::warning(this, "失败", QString("评价提交失败: %1").arg(createResult.second));
            }
        } else {
            // 更新现有评价
            rating.id = existingRating.id;
            RatingOperationResult updateResult = m_ratingManager->updateRating(rating);
            
            if (updateResult == RatingOperationResult::SUCCESS) {
                QMessageBox::information(this, "成功", "评价更新成功！");
                // 延迟刷新，避免潜在问题
                QTimer::singleShot(500, this, [this]() {
                    refreshRatings();
                });
            } else {
                QMessageBox::warning(this, "失败", "评价更新失败");
            }
        }
    }
    
    dialog->deleteLater();
}

void RatingWidget::onOrderCompleted(const QString& orderId)
{
    Q_UNUSED(orderId)
    // 当有订单完成时，立即刷新可评价订单列表
    // 使用短延迟确保数据已经完全更新
    QTimer::singleShot(100, this, [this]() {
        refreshRatings();
    });
}

QString RatingWidget::formatOrderStatus(OrderStatus status) const
{
    return orderStatusToString(status);
}

QString RatingWidget::formatAmount(double amount) const
{
    return QString("¥%1").arg(QString::number(amount, 'f', 2));
}

QString RatingWidget::formatDateTime(const QDateTime& dateTime) const
{
    return dateTime.toString("yyyy-MM-dd hh:mm");
}

Order RatingWidget::getSelectedRatableOrder() const
{
    if (!m_ratableOrderTable || m_ratableOrderTable->currentRow() < 0) {
        return Order();
    }
    
    int row = m_ratableOrderTable->currentRow();
    if (row >= 0 && row < m_ratableOrders.size()) {
        return m_ratableOrders[row];
    }
    
    return Order();
}

Rating RatingWidget::getSelectedRating() const
{
    if (!m_ratingHistoryTable || m_ratingHistoryTable->currentRow() < 0) {
        return Rating();
    }
    
    int row = m_ratingHistoryTable->currentRow();
    if (row >= 0 && row < m_ratingHistory.size()) {
        return m_ratingHistory[row];
    }
    
    return Rating();
}

// ============================================================================
// RatingDialog 实现
// ============================================================================

RatingDialog::RatingDialog(const QString& orderId, QWidget *parent)
    : QDialog(parent)
    , m_orderId(orderId)
    , m_isEditMode(false)
    , m_selectedRating(0)
{
    setWindowTitle("订单评价");
    initializeUI();
    setupOrderInfo();
}

RatingDialog::RatingDialog(const Rating& existingRating, QWidget *parent)
    : QDialog(parent)
    , m_orderId(existingRating.orderId)
    , m_existingRating(existingRating)
    , m_isEditMode(true)
    , m_selectedRating(existingRating.rating)
{
    setWindowTitle("编辑评价");
    initializeUI();
    setupOrderInfo();
    
    // 设置现有评价数据
    if (m_commentEdit) {
        m_commentEdit->setPlainText(m_existingRating.comment);
    }
    
    // 设置评分
    onRatingChanged(m_existingRating.rating);
}

RatingDialog::~RatingDialog()
{
}

Rating RatingDialog::getRating() const
{
    Rating rating;
    
    if (m_isEditMode) {
        rating = m_existingRating;
    } else {
        rating.orderId = m_orderId;
        rating.customerName = ""; // 将由调用者设置
    }
    
    rating.rating = m_selectedRating;
    rating.comment = m_commentEdit ? m_commentEdit->toPlainText() : "";
    rating.createdDate = QDateTime::currentDateTime();
    
    return rating;
}

void RatingDialog::onRatingChanged(int rating)
{
    m_selectedRating = rating;
    
    // 更新星星按钮状态
    for (int i = 0; i < m_starButtons.size(); ++i) {
        QPushButton* button = m_starButtons[i];
        if (i < rating) {
            button->setText("★");
            button->setStyleSheet(R"(
                QPushButton {
                    border: none; 
                    font-size: 28px; 
                    color: #ffd700;
                    background: rgba(255, 215, 0, 0.15);
                    border-radius: 25px;
                }
                QPushButton:hover {
                    color: #ffb300;
                    background: rgba(255, 215, 0, 0.25);
                }
            )");
        } else {
            button->setText("☆");
            button->setStyleSheet(R"(
                QPushButton {
                    border: none; 
                    font-size: 28px; 
                    color: #ddd;
                    background: transparent;
                    border-radius: 25px;
                }
                QPushButton:hover {
                    color: #ffd700;
                    background: rgba(255, 215, 0, 0.1);
                }
            )");
        }
    }
    
    // 更新评分文本
    if (m_ratingTextLabel) {
        m_ratingTextLabel->setText(RatingManager::getRatingLevelText(rating));
    }
    
    // 启用确认按钮并确保样式正确
    if (m_confirmButton) {
        if (rating > 0) {
            // 启用按钮并设置启用样式
            m_confirmButton->setEnabled(true);
            m_confirmButton->setStyleSheet(R"(
                QPushButton {
                    background-color: #667eea;
                    color: white;
                    border: none;
                    border-radius: 18px;
                    padding: 8px 16px;
                    font-size: 13px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background-color: #5a6fd8;
                }
                QPushButton:pressed {
                    background-color: #4d5fc4;
                }
            )");
        } else {
            // 禁用按钮并设置禁用样式
            m_confirmButton->setEnabled(false);
            m_confirmButton->setStyleSheet(R"(
                QPushButton {
                    background: #ccc;
                    color: #999;
                    border: none;
                    border-radius: 18px;
                    padding: 8px 16px;
                    font-size: 13px;
                    font-weight: bold;
                }
            )");
        }
    }
}

void RatingDialog::onConfirmClicked()
{
    if (m_selectedRating <= 0) {
        QMessageBox::information(this, "提示", "请选择评分");
        return;
    }
    
    accept();
}

void RatingDialog::onCancelClicked()
{
    reject();
}

void RatingDialog::initializeUI()
{
    setFixedSize(520, 450);
    setModal(true);
    
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(20, 20, 20, 20);
    m_mainLayout->setSpacing(15);
    
    // 创建滚动区域
    QScrollArea* scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setFrameShape(QFrame::NoFrame);
    scrollArea->setStyleSheet(R"(
        QScrollArea {
            border: none;
            background: transparent;
        }
        QScrollBar:vertical {
            background: #f0f0f0;
            width: 12px;
            border-radius: 6px;
        }
        QScrollBar::handle:vertical {
            background: #c0c0c0;
            border-radius: 6px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background: #a0a0a0;
        }
    )");
    
    // 创建滚动内容容器
    QWidget* scrollContent = new QWidget();
    scrollContent->setStyleSheet("QWidget { background: transparent; }");
    QVBoxLayout* scrollLayout = new QVBoxLayout(scrollContent);
    scrollLayout->setContentsMargins(10, 10, 10, 10);
    scrollLayout->setSpacing(20);
    
    // 订单信息区域
    m_orderInfoGroup = new QGroupBox("订单信息", this);
    QVBoxLayout* orderLayout = new QVBoxLayout(m_orderInfoGroup);
    orderLayout->setContentsMargins(20, 15, 20, 15);
    orderLayout->setSpacing(12);
    
    m_orderIdLabel = new QLabel(this);
    m_orderIdLabel->setStyleSheet("font-size: 14px; color: #333; padding: 5px 0;");
    
    m_orderAmountLabel = new QLabel(this);
    m_orderAmountLabel->setStyleSheet("font-size: 14px; color: #ff6b35; font-weight: bold; padding: 5px 0;");
    
    m_orderDateLabel = new QLabel(this);
    m_orderDateLabel->setStyleSheet("font-size: 13px; color: #666; padding: 5px 0;");
    
    orderLayout->addWidget(m_orderIdLabel);
    orderLayout->addWidget(m_orderAmountLabel);
    orderLayout->addWidget(m_orderDateLabel);
    
    scrollLayout->addWidget(m_orderInfoGroup);
    
    // 评分区域
    m_ratingGroup = new QGroupBox("评分", this);
    QVBoxLayout* ratingMainLayout = new QVBoxLayout(m_ratingGroup);
    ratingMainLayout->setContentsMargins(20, 20, 20, 20);
    ratingMainLayout->setSpacing(15);
    
    m_ratingLayout = new QHBoxLayout();
    m_ratingLayout->setSpacing(15);
    m_ratingLayout->setAlignment(Qt::AlignCenter);
    
    // 创建5个星星按钮
    for (int i = 1; i <= 5; ++i) {
        QPushButton* starButton = new QPushButton("☆", this);
        starButton->setFixedSize(50, 50);
        starButton->setStyleSheet(R"(
            QPushButton {
                border: none; 
                font-size: 28px; 
                color: #ddd;
                background: transparent;
                border-radius: 25px;
            }
            QPushButton:hover {
                color: #ffd700;
                background: rgba(255, 215, 0, 0.1);
            }
        )");
        
        connect(starButton, &QPushButton::clicked, [this, i]() {
            onRatingChanged(i);
        });
        
        m_starButtons.append(starButton);
        m_ratingLayout->addWidget(starButton);
    }
    
    m_ratingTextLabel = new QLabel("请选择评分", this);
    m_ratingTextLabel->setAlignment(Qt::AlignCenter);
    m_ratingTextLabel->setStyleSheet("font-weight: bold; color: #666; font-size: 14px; padding: 10px 0;");
    
    ratingMainLayout->addLayout(m_ratingLayout);
    ratingMainLayout->addWidget(m_ratingTextLabel);
    
    scrollLayout->addWidget(m_ratingGroup);
    
    // 评价内容区域
    m_commentGroup = new QGroupBox("评价内容（可选）", this);
    QVBoxLayout* commentLayout = new QVBoxLayout(m_commentGroup);
    commentLayout->setContentsMargins(20, 15, 20, 15);
    commentLayout->setSpacing(10);
    
    m_commentEdit = new QTextEdit(this);
    m_commentEdit->setFixedHeight(100);
    m_commentEdit->setPlaceholderText("请输入您的评价内容...");
    m_commentEdit->setStyleSheet(R"(
        QTextEdit {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 10px;
            font-size: 13px;
            background: #fafafa;
        }
        QTextEdit:focus {
            border: 2px solid #667eea;
            background: white;
        }
    )");
    
    commentLayout->addWidget(m_commentEdit);
    
    scrollLayout->addWidget(m_commentGroup);
    
    // 为滚动内容添加一些底部空间
    scrollLayout->addStretch(1);
    
    // 设置滚动区域的内容
    scrollArea->setWidget(scrollContent);
    
    // 将滚动区域添加到主布局
    m_mainLayout->addWidget(scrollArea);
    
    // 按钮区域
    m_buttonLayout = new QHBoxLayout();
    m_buttonLayout->setSpacing(15);
    m_buttonLayout->setContentsMargins(0, 20, 0, 0);
    m_buttonLayout->addStretch();
    
    m_confirmButton = new QPushButton(m_isEditMode ? "更新评价" : "提交评价", this);
    m_confirmButton->setFixedHeight(36);
    m_confirmButton->setFixedWidth(100);
    
    // 初始设置为禁用状态并应用禁用样式
    m_confirmButton->setEnabled(false);
    m_confirmButton->setStyleSheet(R"(
        QPushButton {
            background: #ccc;
            color: #999;
            border: none;
            border-radius: 18px;
            padding: 8px 16px;
            font-size: 13px;
            font-weight: bold;
        }
    )");
    
    m_cancelButton = new QPushButton("取消", this);
    m_cancelButton->setFixedHeight(36);
    m_cancelButton->setFixedWidth(80);
    m_cancelButton->setStyleSheet(R"(
        QPushButton {
            background: #f5f5f5;
            color: #666;
            border: 1px solid #ddd;
            border-radius: 18px;
            padding: 8px 16px;
            font-size: 13px;
        }
        QPushButton:hover {
            background: #eee;
            border: 1px solid #ccc;
        }
    )");
    
    connect(m_confirmButton, &QPushButton::clicked,
            this, &RatingDialog::onConfirmClicked);
    connect(m_cancelButton, &QPushButton::clicked,
            this, &RatingDialog::onCancelClicked);
    
    m_buttonLayout->addWidget(m_cancelButton);
    m_buttonLayout->addWidget(m_confirmButton);
    m_buttonLayout->addStretch();
    
    m_mainLayout->addLayout(m_buttonLayout);
    
    applyStyleSheet();
}

void RatingDialog::setupOrderInfo()
{
    // 获取订单信息
    Order order = OrderManager::instance().getOrderById(m_orderId);
    
    if (m_orderIdLabel) {
        m_orderIdLabel->setText(QString("订单编号: %1").arg(order.id));
    }
    
    if (m_orderAmountLabel) {
        m_orderAmountLabel->setText(QString("订单金额: ¥%1").arg(
            QString::number(order.totalAmount, 'f', 2)));
    }
    
    if (m_orderDateLabel) {
        m_orderDateLabel->setText(QString("下单时间: %1").arg(
            order.createdDate.toString("yyyy-MM-dd hh:mm")));
    }
}

void RatingDialog::applyStyleSheet()
{
    setStyleSheet(R"(
        QDialog {
            background: white;
        }
        
        QGroupBox {
            font-weight: bold;
            font-size: 14px;
            color: #333;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            margin: 8px 0;
            padding-top: 20px;
            background: #fafafa;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 15px;
            padding: 0 8px;
            background: white;
            border-radius: 6px;
        }
    )");
}
